package cn.jh.common.interceptor;

import cn.jh.common.utils.RequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.springframework.util.StringUtils.hasText;


public class AuthenticationHeaderInterceptor implements HandlerInterceptor {
	
	private static Logger log = LoggerFactory.getLogger(AuthenticationHeaderInterceptor.class);
	private static ObjectMapper objectMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}

		resolveToken(request);
    	
        return true;
	}

    private void resolveToken(HttpServletRequest request) {
        String authzHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        String token;
        if (hasText(authzHeader) && authzHeader.startsWith("Bearer ")) {
            token = authzHeader.substring(7);
        } else {
            token = request.getParameter("token");
        }
        RequestUtil.setupToken(token);
    }

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	    RequestUtil.clear();
	}


}
